package com.ushine.web.config.database;

/**
 * @Author: user
 * @Date: 2021/4/20 16:33
 * @Description: 日志的数据源jpa配置
 * *              1、注意：注解处basePackages=“****”//此处对应程序dao层 全路径包名
 * *              2、LocalContainerEntityManagerFactoryBean方法下的.packeages(“***”)//pojo类全类名
 * @Version 1.0
 */

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        transactionManagerRef = "logShardPlatformTransactionManager",
        entityManagerFactoryRef = "logShardEntityManagerFactoryBean",
        basePackages = {"com.ushine.web.log.mapper"})
public class JpaLogShardDruidConfig {
    @Resource
    @Qualifier("logDruidDataSource")
    DataSource dataSource;

    @Resource
    JpaProperties jpaProperties;

    @Resource
    private HibernateProperties hibernateProperties;

    @Bean(name = "logEntityManagerSecondary")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return Objects.requireNonNull(entityManagerFactoryBean(builder).getObject()).createEntityManager();
    }

    @Bean(name = "logShardEntityManagerFactoryBean")
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
        Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
                jpaProperties.getProperties(), new HibernateSettings());
        return builder.dataSource(dataSource)
                .properties(properties)
                .packages("com.ushine.web.log.model")
                .persistenceUnit("primaryPersistenceUnit")
                .build();
    }

    @Bean(name = "logShardPlatformTransactionManager")
    PlatformTransactionManager platformTransactionManager(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryBean = entityManagerFactoryBean(builder);
        return new JpaTransactionManager(Objects.requireNonNull(factoryBean.getObject()));
    }
}
